package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.SHOP_GEO_KEY;

/**
 * @desc 商铺加到缓存redis中
 * @author: weili23
 * @params
 * @Date: 2024/3/15 16:57
 * @version: 1.0
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryShopById(Long id) {
        //缓存穿透
        /*Shop shop = getShopInfoCacheCT(id);
        */
        Shop shop = getShopInfoCacheJC(id);
        if (shop == null) {
            return Result.fail("商品不存在！");
        }


        return Result.ok(shop);
    }


    //防止缓存击穿，根据商品id查询商品
    public Shop getShopInfoCacheJC(Long id){
        String key = CACHE_SHOP_KEY+id;
        //从redis中获取
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(shopJson)) {
            //不为空的话 直接返回shop对象
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            log.info("走的shop缓存");
            return shop;
        }
        if("".equals(shopJson)){
            return  null;
        }
        Shop shop = null;
        //redis 为空的话 从数据库取,先获取互斥锁
        String lockKey = "lock:shop:"+id;
        try {
            Boolean flag = tryLock(lockKey,id.toString());
            //加锁是否成功
            if(!flag){
                //失败的话， 休眠重试
                Thread.sleep(50);
                return getShopInfoCacheJC(id);

            }
            shop = getById(id);
            //模拟重建的延时  并发
            //Thread.sleep(200);
            log.info("shop数据库查询");
            if (shop == null) {
                //防止缓存穿透 为空的时候也存入redis  值为"",两分钟有效期
                stringRedisTemplate.opsForValue().set(key,"",2L,TimeUnit.MINUTES);
                return null;
            }
            //商铺存在，保存到redis中 最后返回
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop));
            stringRedisTemplate.expire(key,30L, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //释放锁
            delLock(lockKey);
        }
        return shop;
    }


    //防止缓存穿透，根据商品id查询商品
    public Shop getShopInfoCacheCT(Long id){
        String key = CACHE_SHOP_KEY+id;
        //从redis中获取
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(shopJson)) {
            //不为空的话 直接返回shop对象
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            log.info("走的shop缓存");
            return shop;
        }
        if("".equals(shopJson)){
            return  null;
        }
        //redis 为空的话 从数据库取
        Shop shop = getById(id);
        log.info("shop数据库查询");
        if (shop == null) {
            //防止缓存穿透 为空的时候也存入redis  值为"",两分钟有效期
            stringRedisTemplate.opsForValue().set(key,"",2L,TimeUnit.MINUTES);
            return null;
        }
        //商铺存在，保存到redis中 最后返回
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop));
        stringRedisTemplate.expire(key,30L, TimeUnit.MINUTES);
        return shop;
    }
    //加锁  setnx
    public Boolean tryLock(String key,String value){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, value, 30L, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //释放锁
    public void delLock(String key){
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        if (shop.getId() == null) {
            Result.fail("id为空，不能更新");
        }
        //更新数据库
        updateById(shop);
        //数据库更新成功后，删除原redis
        stringRedisTemplate.delete(CACHE_SHOP_KEY+shop.getId());
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //如果xy没传 从数据库查询
        if(x==null || y==null){ // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //计算分页参数
        int from = (current-1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //如果传了 从redis中查询地理坐标信息
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                SHOP_GEO_KEY + typeId,
                GeoReference.fromCoordinate(x, y),  //传进来的xy坐标信息
                new Distance(5000),  //以xy坐标 5000米以内的距离半径的信息
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)); //查询0-end的数据 后面要截取
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size()<=from){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>(list.size());
        Map<String,Distance> distanceMap= new HashMap<>(list.size());
        //截取
        list.stream().skip(from).forEach(result->{
            String shopId = result.getContent().getName(); //这是存的shopid
            ids.add(Long.valueOf(shopId));
            Distance distance = result.getDistance();
            distanceMap.put(shopId,distance);
        });
        String idsStr = StrUtil.join(",", ids);
        //根据shopid查询shop信息
        List<Shop> shopList = query().in("id", ids).last("ORDER BY FIELD(id," + idsStr + ")").list();
        //把距离放到店铺信息
        for (Shop shop : shopList) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shopList);
    }

    public void copy1(){
        /*String key = CACHE_SHOP_KEY+id;
        //从redis中获取
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(shopJson)) {
            //不为空的话 直接返回shop对象
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            log.info("走的shop缓存");
            return Result.ok(shop);
        }
        if("".equals(shopJson)){
            return  Result.fail("商铺不存在！");
        }
        //redis 为空的话 从数据库取
        Shop shop = getById(id);
        log.info("shop数据库查询");
        if (shop == null) {
            //防止缓存穿透 为空的时候也存入redis  值为"",两分钟有效期
            stringRedisTemplate.opsForValue().set(key,"",2L,TimeUnit.MINUTES);
            return Result.fail("商铺不存在");
        }
        //商铺存在，保存到redis中 最后返回
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop));
        stringRedisTemplate.expire(key,30L, TimeUnit.MINUTES);
        return Result.ok(shop);*/
    }
}
